<template>
  <div class="app-container">
    <div class="filter-container">

      <el-button v-show="listQuery.contractType=='IN'" v-has="'supplyContractInTable_add'" class="filter-item" @click="handleCreate" type="primary" icon="el-icon-plus" >新增合同</el-button>
      <el-button v-show="listQuery.contractType=='OUT'" v-has="'supplyContractOutTable_add'" class="filter-item" @click="handleCreate" type="primary" icon="el-icon-plus" >新增合同</el-button>
     
      <el-button v-show="listQuery.contractType=='IN'" v-has="'supplyContractInTable_mutilDisable'" class="filter-item" @click="handleBatchInvalid" type="primary" icon="el-icon-circle-close-outline" >{{$t('table.batchInvalid')}}</el-button>
      <el-button v-show="listQuery.contractType=='OUT'" v-has="'supplyContractOutTable_mutilDisable'" class="filter-item" @click="handleBatchInvalid" type="primary" icon="el-icon-circle-close-outline" >{{$t('table.batchInvalid')}}</el-button>

      <el-button v-show="listQuery.contractType=='IN'" v-has="'supplyContractInTable_export'" class="filter-item" @click="handleExcelExport" type="primary" icon="el-icon-download" >{{$t('table.excelExport')}}</el-button>
      <el-button v-show="listQuery.contractType=='OUT'" v-has="'supplyContractOutTable_export'" class="filter-item" @click="handleExcelExport" type="primary" icon="el-icon-download" >{{$t('table.excelExport')}}</el-button>
     

      <el-button v-show="listQuery.contractType=='IN'" v-has="'supplyContractInTable_import'" class="filter-item" style="margin-right: 10px" type="primary" icon="el-icon-files-excel" @click="downloadTem">{{$t('table.downloadTem')}}</el-button>

      <el-button v-show="listQuery.contractType=='OUT'" v-has="'supplyContractOutTable_import'" class="filter-item" style="margin-right: 10px" type="primary" icon="el-icon-files-excel" @click="downloadTem">{{$t('table.downloadTem')}}</el-button>

      <el-upload
        class="upload-demo"
        :action="importUrl"
        :on-success="importSuccess"
        :show-file-list="false"
        :beforeUpload="beforeAvatarUpload"
        :headers="uploadHeaders"
       
      >
        <el-button v-show="listQuery.contractType=='IN'" v-has="'supplyContractInTable_import'" class="filter-item" type="primary" icon="el-icon-upload">{{$t('table.batchImport')}}</el-button>
        <el-button v-show="listQuery.contractType=='OUT'" v-has="'supplyContractOutTable_import'" class="filter-item" type="primary" icon="el-icon-upload">{{$t('table.batchImport')}}</el-button>
        
      </el-upload>

      <br/>

      <el-select clearable style="width: 200px" class="filter-item" v-model="listQuery.expireStatus" placeholder="到期状态" @change="handleFilter">
        <el-option v-for="item in $expireOptions" :key="item.key" :label="item.label" :value="item.key">
        </el-option>
      </el-select>

      <el-select clearable style="width: 200px" class="filter-item" v-model="listQuery.balanceType" placeholder="结算形式" @change="handleFilter">
        <el-option v-for="item in $balanceTypeAllOptions" :key="item.key" :label="item.label" :value="item.key">
        </el-option>
      </el-select>

      <el-select clearable style="width: 200px" class="filter-item" v-model="listQuery.contractStatus" placeholder="合同状态" @change="handleFilter">
        <el-option v-for="item in $statusOptions" :key="item.key" :label="item.label" :value="item.key">
        </el-option>
      </el-select>

      <el-input style="width: 300px;" class="filter-item" placeholder="合同编号/合同名称/供应商简称" v-model="listQuery.compoundSearch">
      </el-input>

      <br/>

      <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="handleFilter">{{$t('table.search')}}</el-button>

      <el-button class="filter-item" type="primary" v-waves icon="el-icon-refresh" @click="restQuery">{{$t('table.reset')}}</el-button>

      <br/>



    </div>

    <el-table :key='tableKey' :data="list" v-loading="listLoading" element-loading-text="给我一点时间" border fit highlight-current-row
              style="width: 100%" ref="table"
              @selection-change="selectionChange">
      <el-table-column disabled :selectable='checkboxInit' type="selection" width="35" reserve-selection="" ></el-table-column>
      <el-table-column align="center" :label="$t('table.showId')" width="65">
        <template slot-scope="scope">
          <span>{{scope.row.showId}}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="合同编号">
        <template slot-scope="scope">
          <span>{{scope.row.contractNo}}</span>
        </template>
      </el-table-column>


      <el-table-column align="center" label="合同名称">
        <template slot-scope="scope">
          <span>{{scope.row.contractName}}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="供应商简称" width="100px">
        <template slot-scope="scope">
          <span>{{scope.row.supplyName}}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="到期状态">
        <template slot-scope="scope">
          <span>{{scope.row.expireStatus}}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="协议有效期" width="100px">
        <template slot-scope="scope">
          <span>{{scope.row.mounthNum}}月</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="开始时间">
        <template slot-scope="scope">
          <span>{{scope.row.beginDate | $dateConvert}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="终止时间">
        <template slot-scope="scope">
          <span>{{scope.row.endDate | $dateConvert}}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="结算形式">
        <template slot-scope="scope">
          <span>{{scope.row.balanceType | $balanceTypeAllFilter}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="价格">
        <template slot-scope="scope">
          <span v-show="scope.row.balanceType!='DIVIDE'">{{scope.row.totalAmount}}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="合同状态">
        <template slot-scope="scope">
          <span>{{scope.row.contractStatus | $statusFilter}}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作人">
        <template slot-scope="scope">
          <span>{{scope.row.modifier}}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="修改时间">
        <template slot-scope="scope">
          <span>{{scope.row.modifyTime | $dateConvert("YYYY-MM-DD HH:mm:ss")}}</span>
        </template>
      </el-table-column>


      <el-table-column align="center" :label="$t('table.actions')" width="178" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-show="listQuery.contractType=='IN' && scope.row.contractStatus=='VALID'" v-has="'supplyContractInTable_edit'" type="primary" size="mini" @click="handleUpdate(scope.row)">{{$t('table.edit')}}</el-button>
          <el-button v-show="listQuery.contractType=='OUT' && scope.row.contractStatus=='VALID'" v-has="'supplyContractOutTable_edit'" type="primary" size="mini" @click="handleUpdate(scope.row)">{{$t('table.edit')}}</el-button>

          <el-button v-show="listQuery.contractType=='IN'" v-has="'supplyContractInTable_info'" type="info" size="mini" @click="handleInfo(scope.row,'info')">{{$t('table.info')}}</el-button>
          <el-button v-show="listQuery.contractType=='OUT'" v-has="'supplyContractOutTable_info'" type="info" size="mini" @click="handleInfo(scope.row,'info')">{{$t('table.info')}}</el-button>
        
          <el-button v-show="listQuery.contractType=='IN' && scope.row.contractStatus=='VALID'"   v-has="'supplyContractInTable_disable'" size="mini" type="danger" @click="handleInvalid(scope.row,'invalid')">{{$t('table.invalid')}}</el-button>
          <el-button v-show="listQuery.contractType=='OUT' && scope.row.contractStatus=='VALID'" v-has="'supplyContractOutTable_disable'" size="mini" type="danger" @click="handleInvalid(scope.row,'invalid')">{{$t('table.invalid')}}</el-button>
          

          <el-button v-has="'copyrightsTable'" size="mini" type="info" @click="handleToCopyrights(scope.row.contractNo)">管理版权</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination background @current-change="handleCurrentChange" :current-page="page.page" :page-size="page.limit" layout="total, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>


  </div>
</template>

<script>
  import { fetchList, deleteSupplyContract, invalidSupplyContract, batchInvalid } from '@/api/supplyContract/supplyContract'
  import waves from '@/directive/waves' // 水波纹指令
  import { parseTime } from '@/utils'
  import store from '@/store'

  // const expireOptionsMap = this.GLOBAL.$expireOptions;

  export default {
    name: 'complexTable',
    directives: {
      waves
    },
    data() {
      return {
        tableKey: 0,
        list: null,
        total: null,
        listLoading: true,
        page: {
          page: 1,
          limit: 50,
          sort: ''
        },
        listQuery: {
          compoundSearch: undefined,
          expireStatus: undefined,
          clearMethod: undefined,
          contractStatus: undefined,
          'page.limit': 50,
          'page.sort': 'SHOW_ID',
          'page.order': 'DESC'
        },
        dialogFormVisible: false,
        dialogStatus: '',
        textMap: {
          update: '修改',
          create: '新增',
          info: '详情'
        },
        dialogPvVisible: false,
        pvData: [],
        rules: {
        },
        downloadLoading: false,
        selectIds: '',
        importUrl: process.env.BASE_API + '/supplyContract/importExcel.do',
        addRouteName: 'supplyContractInAdd',
        editRouteName: 'supplyContractInEdit',
        infoRouteName: 'supplyContractInInfo'
      }
    },
    filters: {
    },
    computed: {
      uploadHeaders() {
        if (store.getters.token) {
          return {
            'Authorization': store.getters.token
          }
        }
      }
    },

    created() {
      this.init()
    },
    methods: {
      init() {
        if (this.$route.name === 'supplyContractOutTable') {
          this.listQuery.contractType = 'OUT'
          this.addRouteName = 'supplyContractOutAdd'
          this.editRouteName = 'supplyContractOutEdit'
          this.infoRouteName = 'supplyContractOutInfo'
        } else if (this.$route.name === 'supplyContractInTable') {
          this.listQuery.contractType = 'IN'
        }
        this.getList()
        this.getExpireOption()
      },
      getList() {
        this.listLoading = true
        fetchList(this.listQuery).then(response => {
          if (response.success) {
            this.list = response.content.list
            this.total = response.content.total
            this.listLoading = false
            this.$refs.table.clearSelection()
          } else {
            this.$message({
              type: 'fail',
              message: response.message
            })
          }
        })
      },
      getExpireOption() {
        this.listLoading = true
        fetchList(this.listQuery).then(response => {
          if (response.success) {
            this.list = response.content.list
            this.total = response.content.total
            this.listLoading = false
          } else {
            this.$message({
              type: 'fail',
              message: response.message
            })
          }
        })
      },
      // 搜索按钮
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      // 跳转页数
      handleCurrentChange(val) {
        this.listQuery.page = val
        this.listLoading = true
        this.getList()
      },
      // 详情
      handleInfo(row, status) {
        const id = row.id
        this.$router.push({ name: this.infoRouteName, query: { id: id, opt: 'info' }})
      },
      // 跳转新增页面
      handleCreate() {
        this.$router.push({ name: this.addRouteName, query: { contractType: this.listQuery.contractType }})
      },
      // 更新页面
      handleUpdate(row) {
        const id = row.id
        this.$router.push({ name: this.editRouteName, query: { id: id }})
      },
      // 删除操作
      handleDelete(row) {
        this.$confirm('此操作将永久删除数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then((response) => {
          // 调用删除接口
          var p = { id: row.id }
          deleteSupplyContract(p).then(response => {
            if (response.success) {
              this.getList()
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
            } else {
              this.$message({
                type: 'fail',
                message: response.message
              })
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      // 失效操作
      handleInvalid(row) {
        this.$confirm('失效后，该条数据不可操作，确认失效?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then((response) => {
          // 调用失效接口
          var p = { id: row.id }
          invalidSupplyContract(p).then(response => {
            if (response.success) {
              this.getList()
              this.$message({
                type: 'success',
                message: '操作成功!'
              })
            } else {
              this.$message({
                type: 'fail',
                message: response.message
              })
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          })
        })
      },
      // 初始化页面,批量失效,已失效不允许勾选
      checkboxInit(item) {
        var status = item.contractStatus
        if (status === 'VALID') {
          return 1
        } else {
          return 0
        }
      },
      handleBatchInvalid() {
        // 判断是否选择
        if (!this.selectIds) {
          this.$message({
            type: 'fail',
            message: '请先选择数据，再进行失效操作!'
          })
          return
        }
        // TODO 批量失效
        this.$confirm('失效后，所选数据不可操作，确认失效?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then((response) => {
          // 调用批量失效接口
          var params = { 'invalidIds': this.selectIds }
          batchInvalid(params).then(response => {
            if (response.success) {
              this.getList()
              this.$message({
                type: 'success',
                message: '操作成功!'
              })
            } else {
              this.$message({
                type: 'fail',
                message: response.message
              })
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          })
        })
      },
      handleBatchImport() {
        // TODO 批量导入
      },
      handleExcelExport() {
        this.$alert('导出需要一定时间,请耐心等待', '导出提示', {
          confirmButtonText: '导出',
          callback: action => {
            if (action === 'cancel') {
              return
            }
            this.$message({
              type: 'info',
              message: '正在导出...'
            })
            var params = ''
            for (const field in this.listQuery) {
              const val = this.listQuery[field]
              if (typeof val !== 'undefined' && val !== '') {
                params += field + '=' + val + '&'
              }
            }
  
            if (!params.endsWith('&')) {
              // 加上token
              params += '&'
            }
            params += 'token=' + store.getters.token
            window.open(process.env.BASE_API + '/supplyContract/exportExcel.do?' + params)
          }
        })
      },
      selectionChange(selects) {
        this.selectIds = ''
        for (var select of selects) {
          this.selectIds += select.id
          this.selectIds += ','
        }
        this.selectIds = this.selectIds.substring(0, this.selectIds.length - 1)
      },
      formatJson(filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        }))
      },
      importSuccess(response) {
        if (response.success) {
          this.$message({
            type: 'success',
            message: '导入成功'
          })
          this.getList()
        } else {
          this.$message({
            type: 'fail',
            message: response.message
          })
        }
      },
      // 上传前对文件的类型的判断
      beforeAvatarUpload(file) {
        const extension = file.name.split('.')[1] === 'xls'
        const extension2 = file.name.split('.')[1] === 'xlsx'
        if (!extension && !extension2) {
          this.$message({
            type: 'fail',
            message: '只能上传excel文件'
          })
        }
        return extension || extension2
      },
      downloadTem() {
        window.open(process.env.BASE_URL + '/合同导入模板.xlsx')
      // window.open("http://47.96.144.33:8888/download?filename=%2Fwww%2Fwwwroot%2F%E5%90%88%E5%90%8C%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx");
      },
      handleToCopyrights(contractNo) {
        this.$router.push({ name: 'copyrightsTable', query: { contractNo: contractNo }})
      },
      restQuery() {
        this.listQuery.expireStatus = ''
        this.listQuery.balanceType = ''
        this.listQuery.contractStatus = ''
        this.listQuery.compoundSearch = ''
        this.getList()
      },
      tempConfirm() {
        console.info(2222)
        return false
      }
    },
    watch: {
      '$route'(to, from) {
        // this.$router.go(0)
        this.restQuery()
        this.init()
      }
    }
  }
</script>

<style scoped>

</style>
